package cn.kgc.chlm.dao.impl;

import cn.kgc.chlm.dao.MenuDao;
import cn.kgc.chlm.entity.Menu;
import cn.kgc.chlm.utils.JdbcUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class MenuDaoImpl implements MenuDao {

    private Connection conn;
    private PreparedStatement pstmt;
    private ResultSet rs;

    @Override
    public List<Menu> selectMenuALl() {

        List<Menu> menus = null;
        Menu menu = null;
        try {
            conn = JdbcUtil.getConnection();
            pstmt = conn.prepareStatement("select * from `menu`");
            rs = pstmt.executeQuery();
            menus = new ArrayList<>();
            while (rs.next()){
                menu = new Menu();
                menu.setId(rs.getInt("id"));
                menu.setName(rs.getString("name"));
                menu.setPrice(rs.getDouble("price"));
                menus.add(menu);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return menus;
    }

    @Override
    public Menu selectMenuById(Integer id) {
        Menu menu = null;
        try {
            conn = JdbcUtil.getConnection();
            pstmt = conn.prepareStatement("select * from `menu` where `id` = ?");
            pstmt.setInt(1,id);
            rs = pstmt.executeQuery();

            while (rs.next()){
                menu = new Menu();
                menu.setId(rs.getInt("id"));
                menu.setName(rs.getString("name"));
                menu.setPrice(rs.getDouble("price"));

            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return menu;
    }
}
